$(function(){
	
	var listArr = [{
        "sClass": "trhidden",
        "data": "id",
        "render": function (data, type, full, meta) {
            return '<input type="hidden" class="checkchild"  value="' + data + '" id="check' + data + '"/>';
        },
        "bSortable": false
    },{
    	"sClass": "text-left",
        "data": "sysRoleName"
    }];
	
	var roleTable = function(){
		return matchTable('#datatables','/role/selectAllDataList.do',listArr,false);
	}
	
	roleTable();
	
	ajaxSer.rolePermission(function(data){
			console.log(data);
			var roleList = "";
			for(var i=0; i<data.length; i++){
				var liList = "";
				var rolePer = data[i].listPermission;
				var roleMenu = data[i].listMenu;
				if(roleMenu.length == 0 && rolePer.length > 0){
					for(var j=0; j<rolePer.length; j++){
						liList += '<li><label><input type="checkbox" id="'+ rolePer[j].perId +'">'+ rolePer[j].permissionName +'</label></li>';
					}
					liList = '<ul>'+ liList +'</ul>'
				}else if(roleMenu.length > 0){
					for(var k=0; k<roleMenu.length; k++){
						var twoListRole = roleMenu[k].listPermission;
						var twoListStr = "";
						if(twoListRole.length > 0){
							for(var g=0; g<twoListRole.length; g++){
								twoListStr += '<li><label><input type="checkbox" id="'+ twoListRole[g].perId +'">'+ twoListRole[g].permissionName +'</label></li>'
							}
							twoListStr = '<ul>'+ twoListStr +'</ul>'
						}
						liList += '<div class="ca_twomenu clearfix">' +
											'<div class="ca_twomenuleft">'+ roleMenu[k].sysMenuName +'</div>' +
											'<div class="ca_twomenuright clearfix">' +
											twoListStr +
											'</div>' +
										'</div>';
					}
					
				}
				
				roleList += '<div class="treeflex clearfix">' +
								'<h2>' + data[i].sysMenuName + '<label><input type="checkbox" class="allcheckbox"></label></h2>' +
								liList +
							'</div>';
			}
			$(".roletree").append(roleList);
			
			$(".allcheckbox").on('click',function(){
				if($(this).prop('checked')){
					$(this).parent().parent().parent().find("input").prop('checked',true);
				}else{
					$(this).parent().parent().parent().find("input").prop('checked',false);
				}
			});
	});
	
//	保存
	$(".rolesave").on('click',function(){
		var menuIds = $(".menuId").val();
		var roleIds = [];
		var checkList = $(".roletree input");
		for(var i=0; i<checkList.length; i++){
			if($(checkList[i]).prop('checked') && $(checkList[i]).attr('class') != 'allcheckbox'){
				roleIds.push(parseInt($(checkList[i]).attr('id')));
			}
		}
		var _list = {
			'roleId': menuIds,
			'ids':roleIds
		};
		if(menuIds){
			ajaxSer.rolePerSave(_list,function(data){
				if(data.type == "2"){
					layer.msg(data.msg);
				}
				layer.msg(data.msg);
			})
	   }else{
		   layer.msg('请选择角色！'); 
	   }
	})
	
	
	
	//新增
	$(".roleadd").on('click',function(){
		layer.open({
    	  title: '新增', 
		  skin: 'demo-class',
		  btn: ['确认', '取消'],
		  content: $(".roleaddcont").html(),
		  success: function(layero, index){
			  $(layero).find('#roleForm').validate();
		  },
		  yes:function(index, layero){
			  //这里是回调，点击确认的时候执行的方法，最后一个关闭需要手动调用
			  if($(layero).find('#roleForm').valid()){
				  noClick(layero);
				  var treeJson = $(layero).find('form').serializeObject();
				  ajaxSer.roleAdd(treeJson,function(data){
					  hasClick(layero);
					  if(data.type == "2"){
						 roleTable().draw();
					  }
					  layer.msg(data.msg);
				  },function(){
					  hasClick(layero);
				  });
				  layer.close(index);
			  }
		  },
		  cancel:function(index){
			  layer.close(index);
		  }
		});
	});
	
	//修改
	$(".roleedit").on('click',function(){
		var choose_a = $('#datatables tbody .selected input');
        var c_tIds;
        c_tIds = choose_a.eq(0).val();
        if (c_tIds == undefined || $.trim(c_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
    	layer.open({
    	  title: '修改', 
  		  skin: 'demo-class',
  		  btn: ['确认', '取消'],
  		  content: $(".roleaddcont").html(),
  		  success: function(layero, index){
  			//修改之前执行填充操作
  			$(layero).find('#roleForm').validate();
  			ajaxSer.roleEditPull(c_tIds,function(data){
  				var nameVal = $(layero).find('form input');
				for(var i=0; i<nameVal.length;i++){
					if(data[$(nameVal[i]).attr('name')]){
						$(nameVal[i]).val(data[$(nameVal[i]).attr('name')])
					}
				}
  			});
  		  },
  		  yes:function(index, layero){
  			if($(layero).find('#roleForm').valid()){
  			  noClick(layero);
  			  var treeJson = $.extend({},{'id':c_tIds},$(layero).find('form').serializeObject());
  			  ajaxSer.roleEdit(treeJson,function(data){
  				  if(data.type=="2"){
					  roleTable().draw();
				  }
				  layer.msg(data.msg);
  			  },function(){
  				  
  			  });
  			  layer.close(index);
  			}
  		  },
  		  cancel:function(index){
  			  layer.close(index);
  		  }
  		});
	});
	
	//删除
	$(".roledel").on('click',function(){
		var del_tIds = "";
        var data_a = $("#datatables tbody .selected input");
        $.each(data_a, function (n) {
            if (n == 0) {
                del_tIds = data_a.eq(n).val();
            } else {
                del_tIds = del_tIds + "," + data_a.eq(n).val();
            }
        })
        if (del_tIds == undefined || $.trim(del_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
    	layer.confirm('确认删除?', {icon: 3, title:'删除'}, function(index){
    		ajaxSer.roleDel(del_tIds,function(data){
    			if (data.type == "2") {
                	roleTable().draw();
                }
                layer.msg(data.msg);
    		});
		    layer.close(index);
		});
	});
	
	//单击行选中事件
    $('#datatables tbody').on('click', 'tr', function () {
        var table = $('#datatables').DataTable();
        var data = table.row(this).data();
        $(".menuId").val(data.id);
        $('#datatables tr').removeClass('selected');
        $(this).addClass('selected');
        
        ajaxSer.roleToPermiss(data.id,function(obj){
        	$(".roletree input").prop('checked',false);
			var checkList = $(".roletree input");
			var roleIdPush = [];
			for(var i=0; i<obj.length; i++){
				roleIdPush.push(obj[i].permId);
			}
			for(var j=0; j<checkList.length; j++){
				if($(checkList[j]).attr('class') != "allcheckbox"){
					if(roleIdPush.indexOf(parseInt($(checkList[j]).attr('id'))) != -1){
						$(checkList[j]).prop('checked',true);
					}
				}
			}
        })
    });
});